import { Component, OnInit } from '@angular/core';
import { Router,NavigationExtras,ActivatedRoute } from '@angular/router';
import { HttpClient,HttpErrorResponse} from "@angular/common/http";
import { ActionSheetController,AlertController,ToastController  } from '@ionic/angular';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { CommonResponse,ToastColor,CommonService } from '@services/common-service.service'
import { AuthTokenService } from '@services/auth-token.service'
import { EventEmitterService,EventName } from '../../../../../services/event-emitter.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { DefaultLanguageService } from '@services/default-language.service';
import { TranslateService } from '@ngx-translate/core';
import { CustomToastProviderService,CustomToastOption } from '@common-components/common-toast/custom-toast-provider.service';

@Component({
  selector: 'app-email-amend',
  templateUrl: './email-amend.page.html',
  styleUrls: ['./email-amend.page.scss'],
})
export class EmailAmendPage implements OnInit {

  constructor(private actionSheetController: ActionSheetController,
              private alertController: AlertController,
              private faio:FingerprintAIO,
              public http:HttpClient,
              private route: ActivatedRoute,
              private router:Router,
              private commonService:CommonService,
              private authTokenService:AuthTokenService,
              private eventEmitterService:EventEmitterService,
              private defaultLanguageService:DefaultLanguageService,
              private translate:TranslateService,
              private customToastProviderService:CustomToastProviderService) { }

  public appUserId:string;

  public email:string;

  public i18n:any = {};

  ngOnInit() {
    this.appUserId = this.authTokenService.getAppUserId();
    this.route.queryParams.subscribe((data)=>{
      this.email = data.email;
    });
    this.initLanguage();
  }

  initLanguage(){
    this.i18n = this.commonService.initTranslate(['myAccount.setting.accountScurity.emailEditFunction']);
  }

  async selectAmendType(){
    const actionSheet = await this.actionSheetController.create({
      header: '',
      keyboardClose:true,
      buttons: [
      {
        text: this.i18n.touchId,
        role: '',
        icon: '',
        handler: () => {
          this.checkFingerprintEnable();
        }
      },
      {
        text: this.i18n.login_pwd,
        role: '',
        icon: '',
        handler: () => {
          this.presentPasswordPrompt();
        }
      }, 
      {
        text: this.i18n.cancel,
        icon: '',
        role: 'cancel',
        handler: () => {
          //console.log('Cancel clicked');
        }
      }
      ]
    });
    await actionSheet.present();
  }

  async checkFingerprintEnable(){
    await this.commonService.getAppUser(this.appUserId).subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        if(response.responseBody.fingerPrintLogin){
          this.presentFingerprintPrompt();
        }else{
          this.openEnableFingerprintPrompt();
        }
      }
    });
  }

  async openEnableFingerprintPrompt(){
    const alert = await this.alertController.create({
      header: this.i18n.touch_id_not_available_tip,
      buttons: [
        {
          text: this.i18n.cancel,
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            
          }
        }, {
          text: this.i18n.confirm,
          handler: (data) => {
            this.router.navigate(['tabs/myAccount/setting/fingerprint-setup']);
          }
        }
      ]
    });
    await alert.present();
  }

  presentFingerprintPrompt() {
    this.faio.show({
        title: '',
        fallbackButtonTitle: 'Use Backup',
        disableBackup:true,
    }).then((result: any) => {
      if(result == "biometric_success"){
        this.routerToUpdateEmailPage();
      }else {
        this.commonService.commonToast(ToastColor.warning);
      }
    }).catch((error: any) => {
      //this.commonService.commonToast(ToastColor.warning,"Device not supported Touch ID/Face ID");
    });
  }

  async presentPasswordPrompt() {
    const alert = await this.alertController.create({
      header: this.i18n.please_enter_login_pwd,
      inputs: [
        {
          name: 'password',
          type: 'password',
          placeholder:this.i18n.password
        }
      ],
      buttons: [
        {
          text: this.i18n.cancel,
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            //console.log('Confirm Cancel');
          }
        }, {
          text: this.i18n.confirm,
          handler: (data) => {
            if(!data.password){
              return false;
            }
            this.commonService.checkPassword(data.password).subscribe((response:CommonResponse) => {
              if(response.isSuccess && response.responseBody.isPass){
                this.routerToUpdateEmailPage();
              }else{  
                this.commonService.commonToast(ToastColor.warning,this.i18n.password_incorrent);
              }
            },
            (errorResponse:HttpErrorResponse)=>{
              this.commonService.errorRespCommonToast(errorResponse,this.i18n);
            });
          }
        }
      ]
    });
    await alert.present();
  }

  routerToUpdateEmailPage(){
    this.router.navigate(['/tabs/myAccount/setting/account-security/email-create']);
  }
}
